package com.ruoyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.system.domain.Users;
import com.ruoyi.system.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Primary
public class UserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private UserMapper userMapper;

	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 根据用户名查询用户是否存在
		QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
		usersQueryWrapper.eq("username", username);
		Users users = userMapper.selectOne(usersQueryWrapper);
		if (Objects.isNull(users)) {
			log.info("登录用户：{} 不存在.", username);
			throw new ServiceException(MessageUtils.message("user.not.exists"));
		}
		return createLoginUser(users);
	}
	
	public UserDetails createLoginUser(Users user) {
		return new FrontLoginUser(user);
	}
}

